package io.renren.modules.erp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.JshException;
import io.renren.common.utils.DateTimeUtils;
import io.renren.common.utils.RandomString;
import io.renren.common.utils.StringUtil;
import io.renren.modules.erp.dao.ReturnOrderMapper;
import io.renren.modules.erp.dao.ReturnProductInfoMapper;
import io.renren.modules.erp.dao.SellOrderMapper;
import io.renren.modules.erp.entity.*;
import io.renren.modules.erp.service.*;
import io.renren.modules.erp.vo.ReturnOrderProductVo;
import net.sf.json.JSONArray;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("returnOrderService")
public class ReturnOrderServiceImpl extends ServiceImpl<ReturnOrderMapper, ReturnOrder> implements ReturnOrderService {
    private Logger logger = LoggerFactory.getLogger(ReturnOrderServiceImpl.class);

    @Autowired
    private ReturnOrderMapper returnOrderMapper;
    @Autowired
    private ReturnProductInfoMapper returnProductInfoMapper;
    @Autowired
    ReturnOrderService returnOrderService;
    @Autowired
    ReturnProductService returnProductService;
    @Autowired
    DepotHeadService depotHeadService;
    @Autowired
    SupplierService supplierService;
    @Autowired
    DepotItemService depotItemService;
    @Autowired
    MaterialService materialService;
    @Autowired
    MaterialExtendService  materialExtendService;

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertReturnSellOrder(Long userId)  {
        int result=0;

        //取出这个字段为0的数据
        List<ReturnOrder> listOrder= returnOrderMapper.selectList(new QueryWrapper<ReturnOrder>().eq("is_return_number",0));

        if(listOrder.size()==0||listOrder==null){
            result=1;
            return result;

        }
        //客户表插入客户名
        List<Supplier> list = supplierService.list();
        List<String> supperNames = list.stream().map(Supplier::getSupplier).collect(Collectors.toList());  // 数据库里的
        List<String> collect1 = listOrder.stream().map(ReturnOrder::getMemberCompany).collect(Collectors.toList());
        List<Supplier> suppliers = new ArrayList<>();

        for (String s : collect1) {
            boolean contains = supperNames.contains(s);
            if (!contains){
                Supplier supplier = new Supplier();
                supplier.setSupplier(s);
                suppliers.add(supplier);
            }
        }
        if (CollectionUtils.isNotEmpty(suppliers)){
            supplierService.saveBatch(suppliers);
        }

        List<DepotHead> collect = listOrder.stream().map(item -> {
            DepotHead depotHead = new DepotHead();
            depotHead.setCreateTime(item.getCreateTime().toString());
            depotHead.setExternalNumber(item.getOrderSn());
            depotHead.setContacts(item.getReceiveMan());
            depotHead.setPhoneNum(item.getReceivePhone());
            depotHead.setDeliverAddress(item.getCompanyAddress());
            depotHead.setSupplier(item.getMemberCompany());
            depotHead.setTotalPrice(item.getReturnAmount());
            depotHead.setDocumentStatus(item.getStatus().toString());
            depotHead.setDefaultNumber("XSTH"+ DateTimeUtils.getCurrentDateString().substring(2,8)+ RandomString.getSixRandomString());
            depotHead.setNumber("XSTH"+ DateTimeUtils.getCurrentDateString().substring(2,8)+ RandomString.getSixRandomString());
            depotHead.setType("入库");
            depotHead.setSubType("销售退货");
            depotHead.setStatus("0");
//            depotHead.setTenantId(item.getTenantId());
            depotHead.setDeleteFlag("0");
            depotHead.setServiceType("线上");
            depotHead.setCreator(userId);
            return depotHead;
        }).collect(Collectors.toList());
        depotHeadService.saveBatch(collect);

        List<ReturnOrder> collect2 = listOrder.stream().peek(item -> {
            item.setIsReturnNumber(1);
        }).collect(Collectors.toList());
        returnOrderService.updateBatchById(collect2);
        //取出本次商城订单过来数据的ordersn来查出订单商品
        List<String> collect3 = listOrder.stream().map(ReturnOrder::getOrderSn).collect(Collectors.toList());
        List<ReturnProduct> listProduct=  returnProductInfoMapper.selectList(new QueryWrapper<ReturnProduct>().in("order_sn",collect3));

        //订单编号 orderSn;
        //货品编码  String productNum;
        List<DepotItem> depotItemList  = new ArrayList<>();
        List<Material> materialList  = new ArrayList<>();
        List<MaterialExtend> materialExtendList  = new ArrayList<>();
        List<DepotItem> collect4 = listProduct.stream().map(item -> {
            DepotItem depotItem=new DepotItem();
            Material  material=new Material();
            MaterialExtend materialExtend=new MaterialExtend();
//            depotItem.setHeaderId();
            depotItem.setMaterialId(item.getSkuId());
            depotItem.setUnitPrice(item.getSkuPrice());
            depotItem.setOperNumber(item.getSkuCount());
            depotItem.setAllPrice(item.getRealAmount());

            material.setId(item.getSkuId());
            material.setName(item.getSkuName());

            materialExtend.setMaterialId(item.getSkuId());
            materialExtend.setBarCode(item.getProductNum());
            depotItemList.add(depotItem);
            materialList.add(material);
            materialExtendList.add(materialExtend);
            return depotItem;
        }).collect(Collectors.toList());
        depotItemService.saveBatch(depotItemList);
        materialService.saveBatch(materialList);
        materialExtendService.saveBatch(materialExtendList);

        return result;


    }


    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public void insertReturnOrderProduct(String a1) {
        JSONArray jsonArray = JSONArray.fromObject(a1);
        List<ReturnOrderProductVo> list1=  (List<ReturnOrderProductVo>) jsonArray.toCollection(jsonArray, ReturnOrderProductVo.class);
        //两表根据serviceNumber关联
        Map<String, List<ReturnOrderProductVo>> collect = list1.stream().collect(Collectors.groupingBy(ReturnOrderProductVo::getServiceNumber));
        List<ReturnOrder> returnOrders = new ArrayList<>();
        List<ReturnProduct> productInfoList  = new ArrayList<>();

        for (Map.Entry<String, List<ReturnOrderProductVo>> entry : collect.entrySet()){
            List<ReturnOrderProductVo> productVos = entry.getValue();
            ReturnOrderProductVo returnOrderProductVo = productVos.get(0);
            // 1、封装SPU基本信息
            ReturnOrder returnOrder = new ReturnOrder();
            returnOrder.setCompanyAddress(returnOrderProductVo.getCompanyAddress());
            returnOrder.setCreateTime(returnOrderProductVo.getCreateTime());
            returnOrder.setIsReturnNumber(0);
            returnOrder.setMemberCompany(returnOrderProductVo.getMemberCompany());
            returnOrder.setOrderSn(returnOrderProductVo.getOrderSn());
            returnOrder.setReason(returnOrderProductVo.getReason());
            returnOrder.setReceiveMan(returnOrderProductVo.getReceiveMan());
            returnOrder.setReceivePhone(returnOrderProductVo.getReceivePhone());
            returnOrder.setReturnAmount(returnOrderProductVo.getReturnAmount());
            returnOrder.setServiceNumber(returnOrderProductVo.getServiceNumber());
            returnOrder.setStatus(returnOrderProductVo.getStatus());
            returnOrder.setType(returnOrderProductVo.getType());

            returnOrders.add(returnOrder);
            List<ReturnProduct> productInfoVos = productVos.stream().map(item -> {
                // SKU销售属性
                ReturnProduct productInfo = new ReturnProduct();

                productInfo.setProductNum(item.getProductNum());
                productInfo.setRealAmount(item.getReturnAmount());
                productInfo.setServiceNumber(item.getServiceNumber());
                productInfo.setSkuAttrsVals(item.getSkuAttrsVals());
                productInfo.setSkuCount(item.getSkuCount());
                productInfo.setSkuId(item.getSkuId());
                productInfo.setSkuName(item.getSkuName());
                productInfo.setSkuPrice(item.getSkuPrice());

                productInfoList.add(productInfo);
                return productInfo;
            }).collect(Collectors.toList());
//            productInfoService.saveBatch(productInfoVos);
        }
        returnProductService.saveBatch(productInfoList);
        returnOrderService.saveBatch(returnOrders);
    }
}
